﻿#include "CommandProcessor.h"

#include <sstream>

void process_command(int argc, std::string* argv) {
	std::map<std::string, std::string> arg_map;
	arg_map["audio_format"] = "aac";
	arg_map["audio_path"] = "";
	arg_map["bg_picture_path"] = "";
	arg_map["lyric_path"] = "";
	arg_map["midi_path"] = "";
	arg_map["output_path"] = "";
	arg_map["preset_path"] = "";
	arg_map["record_picture_path"] = "";
	for (int i = 0; i < argc; ++i) {
		const std::string arg = argv[i];

		// 检查基本格式：以"--"开头且包含等号
		if (arg.size() < 4 || arg.substr(0, 2) != "--") {
			std::cout << "[Warning]已忽略无效的参数: " << arg << std::endl;
			continue;
		}

		// 查找等号位置
		size_t eq_pos = arg.find('=');
		if (eq_pos == std::string::npos || eq_pos < 3) {
			std::cout << "[Warning]已忽略无效的参数: " << arg << std::endl;
			continue;
		}

		// 提取参数名（"--"之后，等号之前）
		std::string key = arg.substr(2, eq_pos - 2);

		// 检查参数名是否在预定义列表中
		if (arg_map.find(key) == arg_map.end()) {
			std::cout << "[Warning]已忽略未知的参数: " << arg << std::endl;
			continue;
		}

		// 提取参数值（等号之后）
		std::string value = arg.substr(eq_pos + 1);

		// 处理值两端的引号（单引号或双引号）
		if (value.size() >= 2) {
			char first = value.front();
			char last = value.back();
			if ((first == '\'' && last == '\'') ||
				(first == '\"' && last == '\"')) {
				value = value.substr(1, value.size() - 2);
				}
		}

		// 更新参数映射表
		arg_map[key] = value;
	}
	std::stringstream missing_keys;
	if (arg_map["midi_path"] == "") {
		missing_keys << " midi_path";
	}
	if (arg_map["output_path"] == "") {
		missing_keys << " output_path";
	}
	if (arg_map["preset_path"] == "") {
		missing_keys << " preset_path";
	}
	std::string missing_keys_str = missing_keys.str();
	if (missing_keys_str != "") {
		std::stringstream to_throw;
		to_throw << "命令缺失必需的键：" << missing_keys_str << " 。";
		throw to_throw.str().c_str();
	}
	AudioFormat audio_fmt;
	if (arg_map["audio_format"] == "flac") audio_fmt = AudioFormat::FLAC;
	else if (arg_map["audio_format"] == "aac") audio_fmt = AudioFormat::AAC;
	else if (arg_map["audio_format"] == "") audio_fmt = AudioFormat::AAC;
	else throw "暂不支持audio_format的值。";
	render(
		arg_map["preset_path"], 
		arg_map["midi_path"], 
		arg_map["output_path"], 
		arg_map["bg_picture_path"], 
		arg_map["record_picture_path"], 
		arg_map["audio_path"],
		arg_map["lyric_path"],
		audio_fmt
	);
}